package com.i_art_engineer.meigong.activity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.i_art_engineer.meigong.AppContext;
import com.i_art_engineer.meigong.AppHttpClient;
import com.i_art_engineer.meigong.R;
import com.i_art_engineer.meigong.base.BaseActivity;
import com.i_art_engineer.meigong.base.FullScreenActivity;
import com.i_art_engineer.meigong.util.CountUtil;
import com.i_art_engineer.meigong.widget.ActionBar;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Timer;
import java.util.TimerTask;

import cz.msebera.android.httpclient.Header;

/**
 * 注册界面
 */
public class RegisterActivity extends FullScreenActivity {

    private EditText et_mobile, et_yanzhengma ,et_userid,et_pwd;
    private Button btn_submit,btn_fetchcode;
    private SharedPreferences preferences = AppContext.getPersistPreferences();
    private boolean isget = false;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what>0){
                btn_fetchcode.setText(msg.what+"秒后重新获取。");
                btn_fetchcode.setEnabled(false);
            }else{
                btn_fetchcode.setText("获取验证码");
                btn_fetchcode.setEnabled(true);
                isget = false;

            }

        }
    };

  Thread thread =   new Thread(){
        @Override
        public void run() {
            for (int i = 3;i>=0;i--){
                try {
                    Thread.sleep(1000);
                    handler.sendEmptyMessage(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            for (int i = 3;i>=0;i--){
                try {
                    Thread.sleep(1000);
                    handler.sendEmptyMessage(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    private View.OnClickListener listener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
          final  String mobile = et_mobile.getText().toString();
            String captcha = et_yanzhengma.getText().toString();
            String userid = et_userid.getText().toString();
            final    String pwd = et_pwd.getText().toString();
            switch (v.getId()) {
                case R.id.btn_submit:

                    if(TextUtils.isEmpty(mobile)||TextUtils.isEmpty(captcha)||TextUtils.isEmpty(userid)||TextUtils.isEmpty(pwd)){
                        Toast.makeText(RegisterActivity.this, "必备信息不全，请重新填写！", Toast.LENGTH_SHORT).show();
                    }else {
                        AsyncHttpResponseHandler handler = new JsonHttpResponseHandler(){
                            @Override
                            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                                Log.i("提交,注册", response.toString());
                                //{"code":200,"msg":"注册成功","data":{"ticket":"5YeTQ05ptQFR4lBFife9DpoQFWCskA3qDJ2FbnKENF4"}}

                                try {
                                    int code = response.getInt("code");
                                    String msg = response.getString("msg");
                                    if(code==200) {
                                        JSONObject tokenjson = response.getJSONObject("data");
                                        String token = tokenjson.getString("ticket");
                                        AppContext.setTicket(token);
                                        Toast.makeText(RegisterActivity.this, "提交,注册成功！token="+token, Toast.LENGTH_SHORT).show();
                                        String username = preferences.getString("username","");
                                        String userpwd = preferences.getString("userpwd", "");
                                        boolean userjizhu = preferences.getBoolean("userjizhu", false);

                                        username = new String(Base64.encode(mobile.getBytes("utf-8"),Base64.URL_SAFE));
                                        userpwd = new String(Base64.encode(pwd.getBytes("utf-8"),Base64.URL_SAFE));
                                        preferences.edit().putString("username",username).putString("userpwd", userpwd).putBoolean("userjizhu", true).commit();


                                        setResult(1);
                                        finish();
                                    }else{
                                     //   {"code":201,"msg":"请输入正确的电话号码"}
                                        Toast.makeText(RegisterActivity.this, "注册失败！"+msg, Toast.LENGTH_SHORT).show();
                                        setResult(0);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }catch (UnsupportedEncodingException e){
                                    e.printStackTrace();
                                }

                            }
                        };
                        AsyncHttpClient c = new AsyncHttpClient();
//                        AppHttpClient.setHttpClient(c);
                        String partUrl = "http://www.9fanr.com/app/account/signup";
                        RequestParams params = new RequestParams();
                        params.put("phone", mobile);
                        params.put("name",userid);
                        params.put("pwd",pwd);
                        params.put("os","android");
                        params.put("sms", captcha);
                        c.get(partUrl, params, handler);



                    }
                    break;
                case R.id.btn_fetchcaptcha:

                        if(TextUtils.isEmpty(mobile)) {
                            Toast.makeText(RegisterActivity.this, "必备信息不全，请重新填写！", Toast.LENGTH_SHORT).show();
                        }else{
                            AsyncHttpResponseHandler handler = new JsonHttpResponseHandler(){
                                @Override
                                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                                    Log.i("注册 获取验证码", response.toString());
                                    try {
                                        String msg=response.getString("msg");
                                        Toast.makeText(RegisterActivity.this,msg,Toast.LENGTH_SHORT).show();;
                                    }catch (JSONException e){
                                        e.printStackTrace();
                                    }

                                }
                            };
                            AsyncHttpClient c = new AsyncHttpClient();
//                        AppHttpClient.setHttpClient(c);
                            String partUrl = "http://www.9fanr.com/app/sms/send";
                            RequestParams params = new RequestParams();
                            params.put("phone", mobile);
                            c.get(partUrl, params, handler);
                            Toast.makeText(RegisterActivity.this, "获取验证码", Toast.LENGTH_SHORT).show();

                            CountUtil timeCount= new CountUtil(30000,1000,btn_fetchcode, R.string.btn_fetchcaptcha);//传入了文字颜色值
                            timeCount.start();
                        }








                    //此处调用获取验证码接口

                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        ActionBar actionBar=(ActionBar)findViewById(R.id.actionBar);

        actionBar.setTitleView(getString(R.string.title_register));
        actionBar.setLeftButton(R.drawable.btn_back, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RegisterActivity.this.finish();
            }
        });
        et_mobile = (EditText)findViewById(R.id.et_mobile);

        et_yanzhengma = (EditText)findViewById(R.id.et_yanzhengma);
        et_userid = (EditText)findViewById(R.id.et_userid);
        et_pwd = (EditText)findViewById(R.id.et_renewpassord);
        btn_submit = (Button)findViewById(R.id.btn_submit);
        btn_submit.setOnClickListener(listener);
        btn_fetchcode = (Button)findViewById(R.id.btn_fetchcaptcha);
        btn_fetchcode.setOnClickListener(listener);

    }

}
